<template>
  <div class="login-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      status-icon
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="form.remember">记住我</el-checkbox>
      </el-form-item>

      <div class="form-actions">
        <el-button type="primary" @click="submitForm" :loading="loading">
          登录
        </el-button>
        <div class="action-links">
          <a href="javascript:;" @click="$emit('register')">注册新账号</a>
          <a href="javascript:;">忘记密码？</a>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import api from "@/utils/api";

export default {
  name: "LoginForm",
  emits: ["success", "register"],
  setup(props, { emit }) {
    const formRef = ref(null);
    const loading = ref(false);

    const form = reactive({
      username: "",
      password: "",
      remember: false,
    });

    const rules = {
      username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    };

    const submitForm = async () => {
      if (!formRef.value) return;

      try {
        await formRef.value.validate();
        loading.value = true;

        try {
          // 调用实际的登录API
          const response = await api.post("/auth/login", {
            username: form.username,
            password: form.password,
            remember: form.remember
          });
          
          if (response.data.code === 200) {
            // 保存token到localStorage
            if (response.data.data.token) {
              localStorage.setItem('token', response.data.data.token);
            }
            
            // 触发登录成功事件，传递用户数据
            emit("success", response.data.data);
          } else {
            ElMessage.error(response.data.message || "登录失败");
          }
        } catch (error) {
          // 错误处理
          console.error("登录失败:", error);
          
          // 处理不同类型的错误
          if (error.response) {
            // 服务器返回了错误响应
            const statusCode = error.response.status;
            if (statusCode === 401) {
              ElMessage.error("用户名或密码错误");
            } else if (statusCode === 429) {
              ElMessage.error("登录尝试次数过多，请稍后再试");
            } else {
              ElMessage.error(error.response.data.message || "登录失败");
            }
          } else if (error.request) {
            // 请求已发送但未收到响应
            ElMessage.error("服务器无响应，请检查网络连接");
          } else {
            // 请求配置出错
            ElMessage.error("登录请求失败");
          }
        }
      } catch (error) {
        console.error("表单验证失败");
      } finally {
        loading.value = false;
      }
    };

    return {
      formRef,
      form,
      rules,
      loading,
      submitForm,
    };
  },
};
</script>

<style scoped>
.login-form {
  width: 100%;
}

.form-actions {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.action-links {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.action-links a {
  color: var(--primary-color);
  text-decoration: none;
}

.action-links a:hover {
  text-decoration: underline;
}
</style> 